package gspushmq.v1.subscribe.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import gspushmq.model.AICondition;
import gspushmq.model.ApiMessage;
import gspushmq.model.ApiMessageType;
import gspushmq.model.DataBase;
import gspushmq.util.DateUtil;
import gspushmq.util.GGLogger;
import gspushmq.v1.produce.GGDataStorage;
import gspushmq.v1.subscribe.GGSubscribe;
import gspushmq.v1.subscribe.handler.core.GGApiHandler;

public class GGAiHandlerImpl extends GGApiHandler {

	@SuppressWarnings("unchecked")
	public void handler() {
		
		ApiMessageType apiType = getApiType();
		JSONArray array = getArray();
		
		//已经在处理里 所以移除掉
		GGSubscribe.apiHandlerQueue.remove(apiType);
		JSONArray aiEventList = array;
		
		Set<ApiMessage> set = GGSubscribe.ApiUrlMessage.get(apiType);
		
		for(ApiMessage apiMess : set) {
			String aidStr = apiMess.getAccount_id();
			
			DataBase dataBase = GGDataStorage.ApiBaseMap.get(apiType);
			if(dataBase == null){
				continue;
			}
			Long accountId = Long.valueOf(aidStr);
			String dateStr = dataBase.getBaseDate().get(aidStr);
			
			if(StringUtils.isBlank(dateStr)){
				continue;
			}
			
			String pStr = apiMess.getParams();
			Map<String, String> pMap = JSONObject.parseObject(pStr, Map.class);
			String checkboxCode = pMap.get("checkbox_code");
			if(StringUtils.isBlank(checkboxCode)){
				return;
			}
			
			//获取用户的复选框条件
			List<String> checkBoxCodeList = getCheckBoxCode(checkboxCode);
			//获取自选股默认分组id
			Long groupId = GGProduceUtil.getMyStockGroupList(accountId);
			//获取自选股股票
			List<String> myStockCodesList = GGProduceUtil.getNewMyStockCodesList(Long.valueOf(accountId), null, groupId, 1);
			
			//需要推送的数组
			JSONArray pushArray = new JSONArray();
			if(!myStockCodesList.isEmpty()){
				GGLogger.warn(getClass(), "------account_id：----" + accountId +"------myStockCodesList----" + myStockCodesList);
				//自选股不为空的情况
				//自选股和总列表的交集数组
				JSONArray myStockArray = new JSONArray();
				commonStockMap(aiEventList, myStockCodesList, myStockArray, pushArray, dateStr, checkBoxCodeList, "myStock");
				//没有交集
				if(myStockArray.isEmpty()){
					//说明需要去查询top300的数据
					List<String> top300Stock = GGProduceUtil.StockScore.TOP300.getTop300();
					//top300和总列表的交集数组
					JSONArray top300Array = new JSONArray();
					commonStockMap(aiEventList, top300Stock, top300Array, pushArray, dateStr, checkBoxCodeList, "top300");
					if(top300Array.isEmpty()){
						return;
					}
				}
			}else{
				//自选股为空的情况
				commonStockMap(aiEventList, null, null, pushArray, dateStr, checkBoxCodeList, "top300");
			}
			
			if(!pushArray.isEmpty()){
				//说明需要进行推送啦
				ApiMessageType messType = new ApiMessageType();
				messType.setApi_url(apiMess.getApi_url());
				messType.setReqeust_id(apiMess.getRequest_id());
				messType.setMq_sub_type(apiMess.getMq_sub_type());
				//标记给推送程序
				GGSubscribe.apiActiveQueue.add(messType);
				
				//记录推送的最新时间
				JSONObject finJson = pushArray.getJSONObject(0);
				dataBase.getBaseDate().put(aidStr, finJson.getString("update_date"));
				
				handlerData(apiMess, pushArray, "ai智能推送");
			}
			GGLogger.warn(getClass(), "------account_id：----" + accountId + "------last_update_date--------"+ GGDataStorage.ApiBaseMap.get(apiType).getBaseDate().get(aidStr));
		}
		array.clear();
	}
	
	/**
	 * 获取用户的复选框条件
	 * @param checkboxCode
	 * @return
	 * @author yutao
	 * @date 2018年5月29日下午5:20:57
	 */
	private static List<String> getCheckBoxCode(String checkboxCode) {
		Map<String, String> checkboxMap = AICondition.checkboxMap;
		String[] split = checkboxCode.split(";");
		Set<String> codeSet = new HashSet<>();
		for(String s : split){
			if("all".equals(s)){
				codeSet.addAll(checkboxMap.values());
			}
			if("raise".equals(s)){
				codeSet.addAll(AICondition.riseList);
			}
			if("down".equals(s)){
				codeSet.addAll(AICondition.downList);
			}
			if("event".equals(s)){
				codeSet.addAll(AICondition.eventList);
			}
			String codeStr = checkboxMap.get(s);
			if(StringUtils.isNotEmpty(codeStr)){
				codeSet.add(codeStr);
			}
		}
		return new ArrayList<String>(codeSet);
	}
	
	/**
	 * 总列表和股票池，取交集
	 * @param aiEventList 总列表
	 * @param stockCodesList 股票池
	 * @param stockArray 取得交集的数组
	 * @param pushArray 记录大于订阅时间的数据
	 * @param dateStr 订阅时间
	 * @author yutao
	 * @param checkBoxCodeList 
	 * @param string 
	 * @date 2018年5月29日下午4:58:50
	 */
	public static void commonStockMap(JSONArray aiEventList, List<String> stockCodesList, JSONArray stockArray, JSONArray pushArray, String dateStr, 
							   List<String> checkBoxCodeList, String type) {
		for(int i=0,size=aiEventList.size(); i<size; i++){
			JSONObject map = aiEventList.getJSONObject(i);
			//克隆一份
			JSONObject mapClone = (JSONObject)map.clone();
			mapClone.put("type", type);
			String stockCode = mapClone.getString("stock_code");
			Date date = mapClone.getDate("update_date");
			String checkboxCode = mapClone.getString("checkbox_code");
			Map<String, String> checkboxMap = AICondition.checkboxMap;
			String cMap = checkboxMap.get(checkboxCode);
			if(StringUtils.isNotBlank(cMap)){
				if(checkBoxCodeList.contains(cMap)){
					
					if(stockCodesList!=null && stockArray != null && stockCodesList.contains(stockCode)){
						stockArray.add(mapClone);
						if(DateUtil.compare(date, DateUtil.stringToDate(dateStr, "yyyy-MM-dd HH:mm:ss.SSS"))>0){
							pushArray.add(mapClone);
						}
					}
				}
			}
			
		}
	}

}
